import { isAuth } from "@/helps/auth";
import { RootState } from "@/models";
import { Jwt } from "@/models/auth/dto";
import { Menu } from "antd";
import { RouterState } from "connected-react-router";
import React, { ReactElement } from "react";
import { useSelector } from "react-redux";
import { Link } from "react-router-dom";

interface Props {}

function useActive(current: string, path: string) {
  return current === path ? "ant-menu-item-selected" : "";
}

export default function Navigation(props: Props): ReactElement {
  const state = useSelector<RootState, RouterState>((state) => state.router);
  console.log(state);
  const pathname = state.location.pathname;
  const isHome = useActive(pathname, "/");
  const isShop = useActive(pathname, "/shop");
  const isSignin = useActive(pathname, "/signin");
  const isSignup = useActive(pathname, "/signup");
  const isDashboard = useActive(pathname, getDashboardUrl());

  function getDashboardUrl() {
    let url = "/user/dashboard";
    if (isAuth()) {
      const {
        user: { role },
      } = isAuth() as Jwt;
      if (role === 1) {
        url = "/admin/dashboard";
      }
    }
    return url;
  }

  return (
    <Menu mode="horizontal" selectable={false}>
      <Menu.Item className={isHome}>
        <Link to="/">首页</Link>
      </Menu.Item>
      <Menu.Item className={isShop}>
        <Link to="/shop">商城</Link>
      </Menu.Item>
      {!isAuth() && (
        <>
          <Menu.Item className={isSignin}>
            <Link to="/signin">登录</Link>
          </Menu.Item>
          <Menu.Item className={isSignup}>
            <Link to="/signup">注册</Link>
          </Menu.Item>
        </>
      )}
      {isAuth() && (
        <Menu.Item className={isDashboard}>
          <Link to={getDashboardUrl()}>dashboard</Link>
        </Menu.Item>
      )}
    </Menu>
  );
}
